package com.lock.redsession.lockredsession.controller;

import com.lock.redsession.lockredsession.bean.Product;
import com.lock.redsession.lockredsession.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private ProductService productService;

    @GetMapping("/test")
    public Product getProductById(Integer productId) {

        return productService.getProductById(productId);
    }

    /**
     * 需求：减扣库存
     * @return
     */
    @RequestMapping("/decr")
    public boolean decrstockCount(Integer productId){
        // redis分布式锁的key
        String key = "dec_store_lock_" + productId;

        try {
            Product product = productService.getProductById(productId);

            Thread.sleep(3000);
            //如果库存为空
            if (product.getProductStock()<=0) {
                System.out.println("票已售完！");
                return false;
            }
            //减库存
            product.setProductStock(product.getProductStock()-1);
            System.out.println("已购票："+Thread.currentThread()+"::"+product.getProductId()+"票号");
            System.out.println("还剩余："+product.getProductStock()+"张票");
            //更新库存
            productService.saveProduct(product);

        }catch (Exception e) {
            System.out.println(e.getMessage());
        }finally {

        }

        return true;
    }
}
